﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using SundUnderviser.ModelLayer;

namespace SundUnderviser.DBLayer
{
    public class DBUnderviser
    {
        private SqlCommand dbCmd = null;
        public DBUnderviser()
        {
        }

        public Underviser FindUnderviser(string initialer)
        {
            string sql = @"select navn, initialer from underviser " +
                           " where initialer  = '" + initialer; 

            Console.WriteLine("sql stmt = " + sql);

             dbCmd = DBConnection.GetDbCommand(sql);

            IDataReader dbReader;
            dbReader = dbCmd.ExecuteReader();

            Underviser underviserObj = null;

            if (dbReader.Read())
            {
                try
                {
                    Console.WriteLine("antal felter " + dbReader.FieldCount);
                    Underviser undviserObj = new Underviser();
                    undviserObj.Navn = dbReader["navn"].ToString();
                    undviserObj.Initialer = dbReader["initialer"].ToString();
                              
                    Console.WriteLine("Underviser objekt oprettet");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Underviser objekt ikke oprettet korrekt");
                    underviserObj = null;
                }


            }

            else
            {
                underviserObj = null;
            }
            dbReader.Close();
            DBConnection.Close();
            return underviserObj;
        }


        public List<Underviser> GetAllUnderviser()
        {
            List<Underviser> returnList = new List<Underviser>();
           string sql = @"select navn, initialer from underviser " ;

            SqlCommand dbCmd = DBConnection.GetDbCommand(sql);

            IDataReader dbReader;
            dbReader = dbCmd.ExecuteReader();

            Underviser underviserObj;

            while (dbReader.Read())
            {
                
                Console.WriteLine("antal felter " + dbReader.FieldCount);
                    underviserObj = new Underviser();
                    underviserObj.Navn = dbReader["navn"].ToString();
                    underviserObj.Initialer = dbReader["initialer"].ToString();
                returnList.Add(underviserObj);
            }
            DBConnection.Close();
            return returnList;

        }
    }
}
